package leetcode.每日一题;

import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2022/3/14 11:16
 * @description：https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists/
 */
public class 两个列表的最小索引总和 {
    @Test
    public void test() {
        Solution solution = new Solution();
    }

    class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            int minIdx = Integer.MAX_VALUE;
            List<String> ans = new ArrayList<>();
            Map<String, Integer> map = new HashMap<>();
            for (int i = 0; i < list1.length; i++) {
                map.put(list1[i], i);
            }
            for (int i = 0; i < list2.length; i++) {
                String s = list2[i];
                if (map.containsKey(s)) {
                    int sumIdx = map.get(s) + i;
                    if (sumIdx < minIdx) {
                        minIdx = sumIdx;
                        ans.clear();
                        ans.add(s);
                    } else if (sumIdx == minIdx){
                        ans.add(s);
                    }
                }
            }
            if (ans.size() == 1) {
                return new String[]{ans.get(0)};
            }
            String[] res = new String[ans.size()];
            for (int i = 0; i < ans.size(); i++) {
                res[i] = ans.get(i);
            }
            return res;
        }
    }

}
